import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElSpace,
  ElButton,
  ElRadioGroup,
  ElRadioButton,
  ElIcon,
  ElLink,
  ElMessageBox,
  ElDatePicker,
  ElMessage
} from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { dateFormatObj } from '~/utils/util'
import type { DemandBatchEnum } from './typings'
import SaasTitle from '~/components/SaasTitle'
import AliIcon from '~/components/AliIocn'
import styles from './../index.module.scss'
import ImportExcel from './ImportExcel'
import SurveyTable from './SurveyTable'
import DelistingTable from './DelistingTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import { encode } from 'js-base64'

export default defineComponent({
  props: ['cancel', 'batchNum'],
  setup(props) {
    const userState = useVuexGetters('user', ['permission']) // 按钮权限
    const store = useStore()
    const proSaasTableRef = ref()
    const surveyTable = ref()
    const delistingTable = ref()
    const state = reactive<DemandBatchEnum>({
      discriminateList: [],
      importVisible: false, // 导入 弹窗是否显示
      exportVisible: false, // 导出 弹窗是否显示
      radio: '查勘匹配数据',
      totalTitleVOS: [],
      delistingTime: '',
      datetime: '',
      discriminateArr: ''
    })
    //  数据初始化
    const index = async () => {
      state.discriminateList = []
      const { code, data } = await store.dispatch('base/GetBasebuildbatchTotal', {
        batchNum: props.batchNum
      })
      if (code === 200) {
        data.areaList.forEach((item: any) => {
          state.discriminateList?.push({
            name: item,
            check: false
          })
        })
        state.totalTitleVOS = data.totalTitleVOS
        state.delistingTime = data.delistingTime || '--'
        state.datetime = data.delistingTime.replace('年', '-').replace('月', '-').replace('日', '')
      }
    }
    //  导入
    const handleChangeImportModal = () => {
      state.importVisible = !state.importVisible
      proSaasTableRef.value?.toSearch() // 刷新
    }
    //  区域切换
    const handDiscriminateClick = (value: any) => {
      value.check = !value.check
      const arr = state.discriminateList?.filter((item) => item.check)
      const array = arr?.map((item) => item.name)
      if (state.radio === '查勘匹配数据') {
        surveyTable.value.buildAreasAjax(array?.join(','))
      } else {
        delistingTable.value.buildAreasAjax(array?.join(','))
      }
      state.discriminateArr = array?.join(',')
    }
    //  tabs切换
    const radioGroupChange = () => {
      const arr = state.discriminateList?.filter((item) => item.check)
      const array = arr?.map((item) => item.name)
      if (state.radio === '查勘匹配数据') {
        surveyTable.value.buildAreasAjax(array?.join(','))
      } else {
        delistingTable.value.buildAreasAjax(array?.join(','))
      }
      state.discriminateArr = array?.join(',')
    }
    //  摘牌时间更新
    const onTimeChange = () => {
      ElMessageBox({
        title: '修改摘牌时间',
        // message: () =>
        //   h(ElDatePicker, {
        //     modelValue: state.datetime,
        //     type: 'datetime',
        //     'onUpdate:modelValue': (val: any) => {
        //       state.datetime = dayjs(val).format('YYYY-MM-DD HH:mm')
        //     }
        //   })
        message: (
          <div>
            <ElDatePicker v-model={state.datetime} format="YYYY-MM-DD HH:mm" />
          </div>
        )
      }).then(async () => {
        const timeObj = dateFormatObj(state.datetime)
        const datetime = `${timeObj.year}年${timeObj.month}月${timeObj.date}日 ${timeObj.hours}:${timeObj.minutes}`
        const { code } = await store.dispatch('base/GetBasebuildbatchSetDelistingTime', {
          batchNum: props.batchNum,
          datetime
        })
        if (code === 200) {
          index()
          ElMessage({
            type: 'success',
            message: '操作成功'
          })
        }
      })
    }
    //  刷新
    const refreshClick = () => {
      radioGroupChange()
    }
    //  获取图表URL
    type IframeHTMLAttributes = any
    const ifSrc = ref<IframeHTMLAttributes>('')
    const iframeSrc = async () => {
      const res = await store.dispatch('user/GetMenu')
      if (res.length > 0) {
        res.forEach((item: any) => {
          if (item.children.length > 0) {
            item.children.forEach((row: any) => {
              if (row.path === '/basestation/delisting') {
                ifSrc.value = `${row.remark}?attachParams=${encode(
                  `{"batchNum":"${props.batchNum}"}`
                )}`
              }
            })
          }
        })
      }
    }

    onMounted(() => {
      props?.batchNum && index()
      props?.batchNum && iframeSrc()
    })

    return () => {
      return (
        <ElCard
          v-slots={{
            header: () => (
              <ElSpace class="info-card-header-space">
                <SaasTitle type="primary">
                  {props.batchNum}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  {userState.permission.value.has('basebuild_batch_import_result') && (
                    <ElButton type="primary" onClick={() => handleChangeImportModal()}>
                      <AliIcon type="icon-daoru" />
                      &nbsp; 导入摘牌结果
                    </ElButton>
                  )}
                </SaasTitle>
                <div>
                  {/* <ElButton text type="primary" onClick={refreshClick}>
                    <ElIcon>
                      <Refresh />
                    </ElIcon>
                  </ElButton> */}
                  <ElLink type="primary" underline={false} onClick={refreshClick}>
                    <AliIcon type="icon-zhongzhi" />
                  </ElLink>
                  <ElButton text type="primary" onClick={props.cancel}>
                    返回上一级&nbsp;
                    <AliIcon type="icon-fanhuishangyiji" />
                  </ElButton>
                </div>
              </ElSpace>
            )
          }}
        >
          <ul class={styles['demand-batch-data-list']}>
            <li
              class={{
                [styles['demand-batch-data-item']]: true,
                [styles['demand-batch-data-item-4073ff']]: true
              }}
              style={{ 'border-color': '#4073ff' }}
            >
              <p class={styles['demand-batch-data-num']} style={{ color: '#4073ff' }}>
                {state.totalTitleVOS![0]?.num || 0}
              </p>
              <p class={styles['demand-batch-data-title']}>需求总数</p>
            </li>
            <li
              class={{
                [styles['demand-batch-data-item']]: true,
                [styles['demand-batch-data-item-08AFC6']]: true
              }}
              style={{ 'border-color': '#08AFC6' }}
            >
              <p class={styles['demand-batch-data-num']} style={{ color: '#08AFC6' }}>
                {state.totalTitleVOS![7]?.num || 0}
              </p>
              <p class={styles['demand-batch-data-title']}>摘牌数</p>
            </li>
            <li
              class={{
                [styles['demand-batch-data-item']]: true,
                [styles['demand-batch-data-item-40BD5A']]: true
              }}
              style={{ 'border-color': '#40BD5A' }}
            >
              <p class={styles['demand-batch-data-num']} style={{ color: '#40BD5A' }}>
                {state.totalTitleVOS![8]?.num || 0}
              </p>
              <p class={styles['demand-batch-data-title']}>中标数</p>
            </li>
          </ul>

          <div style="margin-top: 20px;">
            <ElRadioGroup v-model={state.radio} onChange={radioGroupChange} size="large">
              <ElRadioButton label="查勘匹配数据" />
              <ElRadioButton label="摘牌库数据" />
            </ElRadioGroup>
          </div>

          <div class={styles['demand-batch-data-contens']}>
            <div class={styles['demand-batch-data-left']}>
              <ul class={styles['demand-batch-data-contens-list']}>
                {state.discriminateList?.map((item: any) => (
                  <li
                    class={{
                      [styles['demand-batch-data-contens-item']]: true,
                      [styles['demand-batch-data-contens-item-action']]: item.check
                    }}
                    onClick={() => handDiscriminateClick(item)}
                  >
                    {item.name}
                  </li>
                ))}
              </ul>
            </div>
            {/* 摘牌时间 */}
            {state.radio === '摘牌库数据' && (
              <div class={styles['demand-batch-data-contens-time']}>
                <span>摘牌时间：{state.delistingTime}</span>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                {userState.permission.value.has('basebuild_batch_delistingTime') && (
                  <ElLink type="primary" onClick={onTimeChange}>
                    <ElIcon>
                      <Edit />
                    </ElIcon>
                  </ElLink>
                )}
              </div>
            )}
            {state.radio === '查勘匹配数据' ? (
              <SurveyTable
                ref={surveyTable}
                batchNum={props.batchNum}
                discriminateArr={state.discriminateArr}
              />
            ) : (
              <DelistingTable
                ref={delistingTable}
                batchNum={props.batchNum}
                discriminateArr={state.discriminateArr}
              />
            )}
          </div>
          <div style="margin-top: 30px;">
            <iframe style="width: 100%; height: 100vh;" frameborder="0" src={ifSrc.value}></iframe>
          </div>
          {/* 导入 */}
          {state.importVisible && (
            <ImportExcel batchNum={props.batchNum} doCancel={handleChangeImportModal} />
          )}
        </ElCard>
      )
    }
  }
})
